import { useUserStore } from '@/stores'

// 自定义权限指令

function checkPermission(value: string[], el: HTMLElement) {
  if (!Array.isArray(value)) {
    throw new Error("需要配置权限，如 v-permission=\"['admin','user']\"")
  }
  const userStore = useUserStore()
  const ruleNames = userStore.userInfo.ruleNames
  const hasAuth = value.findIndex((item) => ruleNames.includes(item)) != -1
  if (el && !hasAuth) {
    el.parentNode && el.parentNode.removeChild(el)
  }
  return hasAuth
}

export default {
  install(app: any) {
    app.directive('permission', {
      mounted(el: HTMLElement, binding: { value: string[] }) {
        checkPermission(binding.value, el)
      }
    })
  }
}
